import React, {useEffect, useState, useRef, useContext} from 'react';
import axios from "axios";
import {Button, Modal, Table, Form, Input} from "antd";
import {DeleteOutlined, ExclamationCircleOutlined} from "@ant-design/icons";

const {confirm} = Modal;

export default function NewsCategory() {
    const [dataSource, setDataSource] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);

    const addForm = useRef(null)

    useEffect(() => {
        axios.get(`/categories`).then(res => {
            console.log(res.data)
            setDataSource(res.data)
        })
    }, [])

    // 可编辑改完后失去焦点的回调
    const handleSave = (row) => {
        // console.log(row)
        // const newData = [...dataSource];
        // const index = newData.findIndex((item) => row.id === item.id);
        // const item = newData[index];
        // newData.splice(index, 1, { ...item, ...row });
        // ✅ 上面实现的功能与下面一样
        const newData = dataSource.map(item => {
            if (item.id === row.id){
                return {
                    id: row.id,
                    title: row.title,
                    value: row.value,
                }
            }
            return item
        })
        setDataSource(newData)
        axios.patch(`/categories/${row.id}`,{
            title: row.title,
            value: row.value,
        }).then()
    };

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '栏目名称',
                handleSave: handleSave,
            }),
        },
        {
            title: '操作',
            render: (item) => {
                return <div className='noselect'>
                    <Button danger shape="circle" icon={<DeleteOutlined/>} onClick={() => confirmDel(item)}/>
                </div>
            }
        },
    ]

    // 弹出添加栏目对话框
    const showModal = () => {
        setIsModalVisible(true);
    };
    // 点击添加，提交表单
    const onOk = () => {
        // console.log("add",addForm)
        addForm.current.validateFields().then(value => {
            console.log(value)

            // 拿到正确的表单数据后，关闭对话框，清空表单
            setIsModalVisible(false)
            addForm.current.resetFields()

            // 提交表单，post到后端，自动生成id，再设置 dataSource，方便后面的删除和更新
            axios.post('/categories', {
                // 需要添加上 title ，value 两个属性
                "title": value.category,
                "value": value.category,
            }).then(res => {
                // console.log(res)
                setDataSource([...dataSource, {
                    ...res.data,
                }])
            })
        }).catch(err => {
            console.log(err)
        })
    }

    // 删除确认提示框
    const confirmDel = (item) => {
        confirm({
            title: '你确定要删除?',
            icon: <ExclamationCircleOutlined/>,
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                deleteMethod(item)
            },
            onCancel() {
                console.log('取消');
            },
        });
    }

    // 确认删除后执行的函数
    const deleteMethod = (item) => {
        // console.log(item);

        setDataSource(dataSource.filter(data => data.id !== item.id))
        // 后端同步
        axios.delete(`/categories/${item.id}`).then()
    }


    // 可编辑表格
    const EditableContext = React.createContext(null);

    const EditableRow = ({index, ...props}) => {
        const [form] = Form.useForm();
        return (
            <Form form={form} component={false}>
                <EditableContext.Provider value={form}>
                    <tr {...props} />
                </EditableContext.Provider>
            </Form>
        );
    };

    const EditableCell = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
    }) => {
        const [editing, setEditing] = useState(false);
        const inputRef = useRef(null);
        const form = useContext(EditableContext);
        useEffect(() => {
            if (editing) {
                inputRef.current.focus();
            }
        }, [editing]);

        const toggleEdit = () => {
            setEditing(!editing);
            form.setFieldsValue({
                [dataIndex]: record[dataIndex],
            });
        };

        const save = async () => {
            try {
                const values = await form.validateFields();
                toggleEdit();
                handleSave({...record, ...values});
            } catch (errInfo) {
                console.log('Save failed:', errInfo);
            }
        };

        let childNode = children;

        if (editable) {
            childNode = editing ? (
                <Form.Item
                    style={{
                        margin: 0,
                    }}
                    name={dataIndex}
                    rules={[
                        {
                            required: true,
                            message: `${title} is required.`,
                        },
                    ]}
                >
                    <Input ref={inputRef} onPressEnter={save} onBlur={save}/>
                </Form.Item>
            ) : (
                <div
                    className="editable-cell-value-wrap"
                    style={{
                        paddingRight: 24,
                    }}
                    onClick={toggleEdit}
                >
                    {children}
                </div>
            );
        }

        return <td {...restProps}>{childNode}</td>;
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    return (
        <div>
            <Button type={"primary"} onClick={() => showModal()}>添加</Button>

            <Table dataSource={dataSource} columns={columns}
                   rowKey={item => item.id}   // 因为返回的数据中没有 key 属性，所以需要自己设置一个 rowKey
                   components={components}
            />

            <Modal
                visible={isModalVisible}
                title="添加栏目"
                okText="添加"
                okType="primary"
                cancelText="取消"
                onCancel={() => {
                    setIsModalVisible(false);
                }
                }
                onOk={onOk}
            >
                <Form
                    ref={addForm}
                    name="category"
                >
                    <Form.Item
                        label="栏目名称"
                        name="category"
                        rules={[{required: true, message: 'Please input your username!'}]}
                    >
                        <Input/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}